<template>
  <div class="net-row table-row">
    <div class="buy-info">
      <el-input v-model="net.ratio" size="small" @change="handleRatioChange"></el-input>
      <el-select v-model="net.type" size="small">
        <el-option
          v-for="(item, index) in NET_TYPE_LIST"
          :key="index"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input v-model="net.buyTrigger" @change="handleBuyTriggerChange" size="small"></el-input>
      <span>{{ net.buyPrice }}</span>
      <span>{{ net.buyNum }}</span>
      <span>{{ net.buyCost }}</span>
    </div>
    <div class="sell-info">
      <span>{{ net.sellTrigger }}</span>
      <span>{{ net.sellPrice }}</span>
      <span>{{ net.sellNum }}</span>

      <span>{{ sellValue(net) }}</span>
      <span>{{ sellEarning(net) }}</span>
      <span>{{ sellEarningRatio(net) }}%</span>
    </div>

    <div class="operation">
      <el-button type="text" @click="toAdd">添加</el-button>
      <el-button v-if="index" type="text" @click="emit('delete')">删除</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, watch } from 'vue'
import { useNetRow } from './useNetRow'
import type { BaseForm } from './types'
import type { NetRow } from './types'

import { NET_TYPE_LIST } from './model'
import { ElMessage } from 'element-plus'

const props = defineProps<{
  index: number
  baseForm: BaseForm
  lastBuyTrigger: number
  lastRatio: number
}>()

const emit = defineEmits(['add', 'delete'])

const toAdd = () => {
  valid().then(() => {
    emit('add', props.index)
  })
}

export type NetRowProps = typeof props

const {
  net,
  handleRatioChange,
  handleBuyTriggerChange,
  handleBaseTriggerChange,
  handleBaseCostChange
} = useNetRow(props)

const sellValue = computed(() => {
  return (net: NetRow) => {
    const { sellNum, sellPrice } = net
    return (sellNum * sellPrice).toFixed(2)
  }
})

const sellEarning = computed(() => {
  return (net: NetRow) => {
    const { sellNum, sellPrice, buyPrice } = net
    return (sellNum * (sellPrice - buyPrice)).toFixed(2)
  }
})

const sellEarningRatio = computed(() => {
  return (net: NetRow) => {
    const { sellPrice, buyPrice } = net
    return (((sellPrice - buyPrice) / buyPrice) * 100).toFixed(2)
  }
})

const baseCost = computed(() => {
  return props.baseForm.baseCost
})

const baseTrigger = computed(() => {
  return props.baseForm.baseTrigger
})

watch(baseTrigger, () => {
  handleBaseTriggerChange()
})

watch(baseCost, () => {
  handleBaseCostChange()
})

const valid = () => {
  return new Promise((resolve, reject) => {
    const { ratio, buyTrigger } = net.value
    if (ratio && buyTrigger) {
      resolve(net.value)
    } else {
      ElMessage.error(`请检查第${net.value.ratio}档填写是否正确`)
      reject(net.value)
    }
  })
}

defineExpose({
  net,
  valid
})
</script>

<style lang="scss" scoped>
@import './style.scss';
.net-row {
  width: 100%;
}
</style>
